import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, DatePicker, Popover, Input, Card, Select, Modal } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import { QueryChargeSettleListParams, ChargeSettle, exportChargeSettle } from './services';
import { queryChargeSettleList } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import StationSelect from '@/components/StationSelect';
import Ellipsis from '@/components/Ellipsis';
import dayjs from 'dayjs';
import { EquipmentType } from '@/pages/station/stubList/services';
import { CheckCircleFilled } from '@ant-design/icons';
import { jump2target } from '@/utils/common';
import { exportStation } from '@/pages/order/chargeOrder/services';

const ChargeSettlePage: React.FC<RoutePageProps> = (props) => {
  const [searchForm] = Form.useForm<QueryChargeSettleListParams>()
  const expReq = useRequest(exportChargeSettle, {manual: true})
  const [searchParams, setSearchParams] = useState<QueryChargeSettleListParams>({
    pageNum: 1, pageSize: 10,
    beginDay: dayjs().subtract(31, 'days').format('YYYYMMDD'),
    endDay: dayjs().format('YYYYMMDD'),
  })
  const list = useRequest(() => queryChargeSettleList(searchParams), {
    refreshDeps: [searchParams],
  })

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      stationId: formValues.station ? formValues.station[0]?.id : undefined,
      stationName: formValues.station ? formValues.station[0]?.name : undefined,
      beginDay: formValues.timeRange[0]?.format('YYYYMMDD'),
      endDay: formValues.timeRange[1]?.format('YYYYMMDD'),
      orderCode: undefined,
      stationType: formValues.stationType,
      platOrderCode: undefined,
      [formValues.orderType]: formValues.orderCode,
      pageNum: 1,
    })
  }

  const exportExcel = () => {
    const formValues = searchForm.getFieldsValue()
    const _params = {
      ...searchParams,
      stationId: formValues.station ? formValues.station[0]?.id : undefined,
      stationName: formValues.station ? formValues.station[0]?.name : undefined,
      beginDay: formValues.timeRange[0]?.format('YYYYMMDD'),
      endDay: formValues.timeRange[1]?.format('YYYYMMDD'),
      orderCode: undefined,
      stationType: formValues.stationType,
      platOrderCode: undefined,
      [formValues.orderType]: formValues.orderCode,
      pageNum: 1,
    }
    expReq.runAsync(_params)
      .then(res => {
        Modal.confirm({
          icon: <CheckCircleFilled style={{color: 'red'}} />,
          content: '导出申请成功，请前往导出记录查看文档。',
          onOk: () => {
            jump2target('/report/exportUrl')
          }
        })
      })
  }

  const columns: ColumnsType<ChargeSettle> = [
    {
      title: '订单信息',
      children: [
        {
          title: '结算单号',
          dataIndex: 'id',
          width: 120,
          render: val => <Popover content={val}>
            <Ellipsis style={{width: 100}}>{val || '--'}</Ellipsis>
          </Popover>
        },
        {
          title: '平台订单号',
          dataIndex: 'orderId',
          width: 120,
          render: val => val || '--'
        },
        {
          title: '场站名称',
          dataIndex: 'stationName',
          width: 160,
          render: val => val ? <Popover content={val}><Ellipsis>{val}</Ellipsis></Popover> : null
        },
        {
          title: '枪编号',
          dataIndex: 'stubId',
          width: 100,
        },
        {
          title: '设备类型',
          dataIndex: 'stubType',
          width: 100,
          render: val => EquipmentType[val]
        },
        {
          title: '充电开始时间',
          dataIndex: 'timeBegin',
          width: 140,
          render: val => dayjs(val).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
          title: '充电结束时间',
          dataIndex: 'timeEnd',
          width: 140,
          render: val => dayjs(val).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
          title: '充电量(度)',
          dataIndex: 'power',
          width: 120,
          render: val => val?.toLocaleString(),
        },
        {
          title: '结算出账日期',
          dataIndex: 'createDay',
          width: 140,
        },
      ],
    },
    {
      title: '订单原价信息',
      children: [
        {
          title: '充电金额(元)',
          key: 'chargeMoney',
          width: 120,
          render: (_, record) => {
            const _total = parseFloat((record.electricMoney + record.serviceMoney).toFixed(2))
            return _total.toLocaleString()
          }
        },
        {
          title: '充电电费(元)',
          dataIndex: 'electricMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
        {
          title: '充电服务费(元)',
          dataIndex: 'serviceMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
      ],
    },
    {
      title: '订单结算信息',
      children: [
        {
          title: '充电金额(元)',
          key: 'chargeSettleMoney',
          width: 120,
          render: (_, record) => {
            const _total = parseFloat((record.settleElectricMoney + record.settleServiceMoney).toFixed(2))
            return _total.toLocaleString()
          }
        },
        {
          title: '充电电费(元)',
          dataIndex: 'settleElectricMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
        {
          title: '充电服务费(元)',
          dataIndex: 'settleServiceMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
      ],
    },
    {
      title: '通道信息',
      children: [
        {
          title: '通道费',
          dataIndex: 'pathMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
      ]
    },
    {
      title: '抽成信息',
      children: [
        {
          title: '场地方抽成',
          dataIndex: 'ownerMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
        {
          title: '平台抽成',
          dataIndex: 'platGetMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
        {
          title: '私桩主抽成',
          dataIndex: 'personMoney',
          width: 120,
          render: val => val?.toLocaleString(),
        },
        // {
        //   title: '运营方抽成',
        //   dataIndex: 'workMoney',
        //   width: 120,
        //   render: val => val?.toLocaleString(),
        // },
      ]
    },
  ]

  useEffect(() => {
    if (props.params.sKey) {
      const _paramsStr = sessionStorage.getItem(props.params.sKey.split('___')[0])
      if (_paramsStr) {
        const _params = JSON.parse(_paramsStr)
        let __params: any = undefined
        if (props.params.sKey.startsWith('_searchParams_settleDetail')) {
          __params = {
            station: [{
              id: _params.stationId,
              name: _params.stationName,
            }],
            orderType: 'orderCode',
            stationType: _params.stationType,
            orderCode: _params.settleId,
            timeRange: [dayjs(_params.beginDay), dayjs(_params.endDay)],
          }
        }
        if (__params) {
          searchForm.setFieldsValue(__params)
          onFinish(__params)
        }
      }
    }
  }, [])

  return (
    <div className='container'>
      <Card>
        <div className="search-card">
          <Form name='searchChargeSettleForm' form={searchForm} onFinish={onFinish} initialValues={{
            timeRange: [dayjs().subtract(31, 'days'), dayjs()], orderType: 'orderCode',
          }}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='场站ID' name='station'>
                  <StationSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='电站类型' name='stationType'>
                  <Select placeholder='请选择' options={[
                    {label: '公站', value: '1'},
                    {label: '私站', value: '2'},

                  ]} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='订单号'>
                  <Space.Compact style={{width: '100%'}}>
                    <Form.Item name='orderType' noStyle>
                      <Select options={[
                        {label: '业务订单号', value: 'orderCode'},
                        {label: '平台订单号', value: 'platOrderCode'},
                      ]} style={{width: 120}} />
                    </Form.Item>
                    <Form.Item name='orderCode' noStyle>
                      <Input placeholder='请输入' />
                    </Form.Item>
                  </Space.Compact>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='结算时间' name='timeRange'>
                  <DatePicker.RangePicker allowClear={false} style={{width: '100%'}} disabledDate={current => current.isAfter(dayjs(), 'day')} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                  <Button onClick={exportExcel} loading={expReq.loading}>导出</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </Card>
      <Card title='充电结算明细'>
        <Table<ChargeSettle>
          rowKey='id'
          bordered
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </Card>
    </div>
  );
};

export default ChargeSettlePage;
